package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func _query(ctx *gin.Context) {
	log.Println(ctx.Query("user"))
	log.Println(ctx.GetQuery("user"))
	log.Println(ctx.GetQueryArray("user"))
}

// 动态参数
func _param(ctx *gin.Context) {
	log.Println(ctx.Param("type"))
	log.Println(ctx.Param("hashID"))
}

func _form(ctx *gin.Context) {
	log.Println(ctx.PostForm("username"))
	log.Println(ctx.PostFormArray("username"))
	log.Println(ctx.MultipartForm())
}

func _raw(ctx *gin.Context) {
	data, _ := ctx.GetRawData()
	contentType := ctx.GetHeader("Content-Type")
	log.Println(contentType)
	switch contentType {
	case "application/json":
		type userInfo struct {
			Name string `json:"username"`
			Age  int    `json:"age"`
		}
		user1 := &userInfo{}
		json.Unmarshal(data, user1)
		fmt.Println(user1)
	}
}

func _bindJson(ctx *gin.Context, obj any) (err error) {
	data, _ := ctx.GetRawData()
	contentType := ctx.GetHeader("Content-Type")
	switch contentType {
	case "application/json":
		err := json.Unmarshal(data, obj)
		if err != nil {
			return err
		}
	}
	return nil
}

func bindJson(ctx *gin.Context) {
	type userInfo struct {
		User string `json:"username"`
		Age  int    `json:"age"`
	}
	user1 := &userInfo{}
	_bindJson(ctx, user1)

	log.Println(user1)
}
func main() {
	router := gin.Default()

	router.GET("/user", _query)
	router.GET("/auth/:type/:hashID", _param)
	router.POST("/form", _form)
	router.POST("/raw", _raw)
	router.POST("/bindJson", bindJson)
	router.Run(":8080")

}
